﻿using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Poplar.Passport.IServices;

namespace Poplar.Passport.Portal.Controllers
{
    public class UserController : BaseController
    {
        private readonly IUserService _service;

        public UserController(IUserService service)
        {
            this._service = service;
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Login()
        {
            return View();
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <param name="returnUrl"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Login(string userName, string password, string returnUrl)
        {
            if (userName == null || userName.Length < 5 || password == null || password.Length < 5)
            {
                return Json(new { status = 1, msg = "无效的用户名或者密码！" });
            }
            var user = await this._service.Login(userName, password);
            if (user == null)
            {
                return base.Json(base.Result(1, "用户名或密码错误！"));
            }
            HttpContext.Session.SetString("user", JsonConvert.SerializeObject(user));
            if (string.IsNullOrWhiteSpace(returnUrl))
            {
                returnUrl = "http://kanban.zyshan.com";
            }

            return Json(base.Result(returnUrl));
        }

        /// <summary>
        /// register for ajax
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Register()
        {
            return Content("");
        }
    }
}